package com.cust.zy.newtask.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.renderscript.Allocation;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.cust.zy.newtask.model.Word;
import com.cust.zy.newtask.tools.FileTool;
import com.cust.zy.newtask.tools.TaskResult;
import com.cust.zy.newtask.R;
import com.cust.zy.newtask.dao.DataOperation;
import com.cust.zy.newtask.model.Task;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by zhuangyuan on 4/12/2017.
 * 邮箱：zhuangyuan.k@qq.com
 */
public class NewTaskActivity extends AppCompatActivity {
    private final static String LOG = "NewTaskActivity";
    private final int ACTION_GET_CONTENT=1;
    private EditText taskName;
    private Button taskFileName;
    private RadioGroup taskType;
    private EditText taskDescription;
    private DataOperation dataOperation;
    private ProgressBar progressBar;
    //private View newTaskPanel;
    public static final String FILENAME_MESSAGE="FILENAME_MESSAGE";
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            taskFileName.setText(bundle.getString(FILENAME_MESSAGE));
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_task);
        dataOperation = new DataOperation(NewTaskActivity.this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_new_plan);
        progressBar = (ProgressBar) toolbar.findViewById(R.id.toolbar_progress_bar);
        toolbar.setTitle("创建任务");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //newTaskPanel = this.findViewById(R.id.new_task_panel);
        taskName = (EditText) this.findViewById(R.id.new_task_name);
        taskFileName = (Button) this.findViewById(R.id.new_task_select_file);
        taskType = (RadioGroup) this.findViewById(R.id.new_task_type);
        taskDescription = (EditText) this.findViewById(R.id.new_task_description);
        Button subButton = (Button) this.findViewById(R.id.new_task_subBtn);
        taskFileName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                startActivityForResult(Intent.createChooser(intent, "选择文件"), ACTION_GET_CONTENT);
            }
        });
        subButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RadioButton radioButton = (RadioButton)findViewById(taskType.getCheckedRadioButtonId());
                UUID taskID = UUID.randomUUID();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Task task = new Task(taskID.toString(),taskName.getText().toString(),Integer.valueOf(radioButton.getText().toString()),
                        0,format.format(new Date()),taskDescription.getText().toString(),taskFileName.getText().toString());
                progressBar.setVisibility(View.VISIBLE);
                RegisterTask registerTask = new RegisterTask(task);
                registerTask.execute();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ACTION_GET_CONTENT:
                Uri uri = data.getData();
                String filePath = FileTool.getOriginalFilePath(NewTaskActivity.this, uri);
                Message m = new Message();
                Bundle bundle = new Bundle();
                bundle.putString(FILENAME_MESSAGE, filePath);
                m.setData(bundle);
                handler.handleMessage(m);
                break;
        }
    }
    private class RegisterTask extends AsyncTask<String, Object, TaskResult<List<Word>>> {
        private Task task;
        public RegisterTask(Task task) {
            this.task = task;
        }

        private List<Word> getWords(String filePath) throws IOException {
            List<Word> list = new ArrayList<Word>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            String line;
            int wordCount = 0;
            while((line=reader.readLine())!=null){
                wordCount++;
                Word word = new Word();
                word.setID(UUID.randomUUID().toString());
                word.setName(line.split(" ")[0]);
                word.setTranslation(line.split(" ")[1]);
                word.setTaskID(task.getID());
                String type = "";
                if(wordCount/10%10%2==1){
                    type = (Integer.parseInt(wordCount%10+"")+1)+"";
                }else{
                    type = (Integer.parseInt("1"+wordCount%10)+1)+"";;
                }
                word.setList(type);
                list.add(word);
                line=reader.readLine();
            }
            task.setNumOfWord(wordCount);
            return list;
        }

        @Override
        protected TaskResult<List<Word>> doInBackground(String... arg0) {
            try{
                if(task.getFileName()==""||task.getFileName()==null){
                    return new TaskResult<List<Word>>(new Exception("请选择文件"));
                }
                else if(task.getName()==""||task.getName()==null){
                    task.setName("task_"+task.getGenerateTime());
                }
                List<Word> list = getWords(task.getFileName());
                try {
                    dataOperation.insertIntoTask(task);
                } catch (Exception e) {
                    Log.e(LOG,e.toString());
                }
                return new TaskResult<List<Word>>(list);
            }
            catch(Exception e){
                return new TaskResult<List<Word>>(e);
            }
        }
        @Override
        protected void onPostExecute(TaskResult<List<Word>> result) {
            if(result.isValid()){
                InsertWordsTask insertWordsTask  = new InsertWordsTask(result.getResult());
                insertWordsTask.execute();
            }
            else{
                Log.e(LOG,result.getException().toString());
            }
        }
    }
    private class InsertWordsTask extends AsyncTask<String, Object, TaskResult<Boolean>> {
        private List<Word> list;

        public InsertWordsTask(List<Word> list) {
            this.list = list;
        }
        @Override
        protected TaskResult<Boolean> doInBackground(String... arg0) {
            try {
                try {
                    for(Word word:list){
                        dataOperation.insertIntoWord(word);
                    }
                } catch (Exception e) {
                    Log.e(LOG, e.toString());
                }
                return new TaskResult<Boolean>(true);
            } catch (Exception e) {
                return new TaskResult<Boolean>(e);
            }
        }

        @Override
        protected void onPostExecute(TaskResult<Boolean> result) {
            if(result.isValid()){
                Intent intent = new Intent(NewTaskActivity.this, TaskListActivity.class);
                startActivity(intent);
                finish();
            }
        }
    }
}
